package net.maxwoods.nimble.spring.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.servlet.http.HttpServletRequest;

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final Logger logger=LoggerFactory.getLogger(SecurityConfiguration.class);

    @Autowired
    private AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource;


    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;


    //@Autowired
    //AuthenticationManagerBuilder authenticationManagerBuilder;

    //@Autowired
    //private AuthenticationManager authenticationManager;

    /*
    @Bean
    public SpringTemplateEngine templateEngine(TemplateResolver reslover){
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(reslover);
        templateEngine.addDialect(new SpringSecurityDialect()); //注册安全方言
        return templateEngine;
    }*/

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        //auth.authenticationProvider(new CustomAuthenticationProvider());
        auth.authenticationProvider(customAuthenticationProvider);
    }

    /*
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.inMemoryAuthentication().withUser("maxwoods")
                .password("maxwoods").authorities("ROLE_ADMIN").and().withUser("admin")
                .password("admin").authorities("ROLE_USER","ROLE_ADMIN");
    }*/


    @Override
    public void configure(WebSecurity security)
    {
        security.ignoring().antMatchers("/resource/**");
    }

    @Override
    protected void configure(HttpSecurity security) throws Exception
    {
        String loginPage="/login";
//        security.authorizeRequests().anyRequest().authenticated()
//                .antMatchers("/signup").permitAll()
//                .and().formLogin().loginPage(loginPage).defaultSuccessUrl("/")
//                .authenticationDetailsSource(authenticationDetailsSource)
//                .usernameParameter("userName").passwordParameter("password").permitAll();
        security.authorizeRequests()
                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
                .and()
                .formLogin().loginPage(loginPage)
                .authenticationDetailsSource(authenticationDetailsSource)
                .defaultSuccessUrl("/welcome").failureUrl("/login?error")
                .usernameParameter("user-name").passwordParameter("pwd")
                .and()
                .logout().logoutSuccessUrl("/login?logout")
                .and()
                .csrf();
        logger.info("============={}",authenticationManager());
        CustomLoginFilter customLoginFilter=new CustomLoginFilter("/login2");
        customLoginFilter.setAuthenticationManager(authenticationManager());
        //customLoginFilter.setPostOnly(false);
        security.addFilterBefore(customLoginFilter, UsernamePasswordAuthenticationFilter.class);
        // 加入自定义UsernamePasswordAuthenticationFilter替代原有Filter
       // security.addFilterAt(new CustomLoginFilter(),CustomLoginFilter.class);



    }

    /*
    @Autowired
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        logger.info("{}",authenticationManagerBuilder);
        return authenticationManagerBuilder.build();
    }*/
}
